<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 
            思路：先序遍历BST每一个节点，记录对应的父节点，然后如果当前节点为空，就可以插入其父节点的孩子中。
            这是因为BST的性质，你遍历一定会遍历到对应的空节点的
            */
            var insertIntoBST = function (root, val) {
                if (!root) return null
                //初始化父节点
                let parent = new TreeNode(0)
                function preOrder(cur, val) {
                    //遍历到节点不存在了
                    if (cur == null) {
                        let node = new TreeNode(val)
                        if (parent.val > val) {
                            parent.left = node
                        } else {
                            parent.right = node
                        }
                        //注意，必须有个return，因为null.val会报错
                        return
                    }
                    //记录父节点
                    parent = cur
                    if (cur.val > val) {
                        preOrder(cur.left, val)
                    }
                    if (cur.val < val) {
                        preOrder(cur.right, val)
                    }
                }
                preOrder(root, val)
                return root
            }
        </script>
    </body>
</html>
